package org.zjt.rabbit.demo.delay;

import java.util.HashMap;
import java.util.Map;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.zjt.rabbit.demo.common.ContantsConfig;


/**
 * 延时任务： 一般使用MQ来实现，不用redis来实现。因为redis会丢数据。（redis订阅key超时事件）
 */
public class Producer {

    // 目的队列
    private final static String DESTINATION_QUEUE_NAME = "DESTINATION_QUEUE_NAME";

    // 延时队列：存储缓存的队列，该队列中是一些未到ttl时间的消息。
    private final static String DELAY_NAME = "DELAY_NAME";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ContantsConfig.MQ_HOST);
        factory.setUsername(ContantsConfig.USER);
        factory.setPassword(ContantsConfig.PASSWORD);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        Map<String, Object> arguments = new HashMap();
        arguments.put("x-message-ttl", 10000);                                  // 设置延时时间   10秒延时
        arguments.put("x-dead-letter-exchange", "");
        arguments.put("x-dead-letter-routing-key", DESTINATION_QUEUE_NAME);
        channel.queueDeclare(DELAY_NAME, false, false, false, arguments);
        for (int i = 0; i < 5; i++) {
            String message = "Hello World!";
            channel.basicPublish("", DELAY_NAME, null, message.getBytes("UTF-8"));
            System.out.println("P [x] Sent '" + message + "'");
        }
        channel.close();
        connection.close();
    }
}